import 'dart:math';

import 'package:dsp_bt_audio/modules/dialog_alert.dart';
import 'package:dsp_bt_audio/modules/dialog_bluetooth.dart';
import 'package:dsp_bt_audio/modules/dialog_infomation.dart';
import 'package:dsp_bt_audio/modules/dialog_setup.dart';
import 'package:dsp_bt_audio/modules/model.dart';
import 'package:dsp_bt_audio/tool/assets.dart';
import 'package:flutter_kit_dsp/flutter_kit_dsp.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../lang/my_i19n.dart';
import 'dialog_intput.dart';

class MyHomeController extends HomeController {
  RxList<Model> list1 = <Model>[].obs;
  RxList<Model> list2 = <Model>[].obs;
  late final DialogInfomation dialog_app;
  late final DialogBluetooth dialog_bluetooth;
  late final DialogSetup dialog_setup;
  RxList<String> language_list = [''].obs;
  RxInt currentLanguage = 0.obs;
  RxInt currentIndex = 100.obs;
  RxBool ismute = false.obs;
  RxString reset_title = ''.obs;
  RxList<String> get items {
    final list1 = [assets.voice, assets.app, assets.bluetooth, assets.settings];
    final list2 = [assets.voice_select, assets.app_select, assets.bluetooh_select, assets.settings_select];
    final result = List<String>.from(list1);
    if (currentIndex.value >= 1 && currentIndex.value < list1.length) {
      result[currentIndex.value] = list2[currentIndex.value];
    }
    result[0] = ismute.value ? list2[0] : list1[0];
    result[2] = BluetoothManager.instance.isConnectedRx ? list2[2] : list1[2];
    return result.obs;
  }

  RxList<Map<String, Map<String, dynamic>>> setting_config = <Map<String, Map<String, dynamic>>>[].obs;

  @override
  void onInit() {
    super.onInit();

    homeController.receiveCompletion = () {
      onInit();
      ismute.value = globalController.rxModel.value.ch_list[0].mute;
    };

    final ch = globalController.rxModel.value.ch_list[0];
    ch.select = true;
    final low = ch.low_pass!;
    final sign = ch.sign_list.firstWhere(($0) => $0.select, orElse: () => ch.sign_list.first);
    list1.value = [
      ///通道音量
      Model(title: I19n.i.volume, value: ch.db.obs, min: ch.min_db, max: ch.max_db, step: 1),
      //正反向
      Model(title: I19n.i.phase, value: 0.toDouble().obs, min: 0, max: 180, step: 1),
      //低通频率
      Model(
        title: I19n.i.low,
        value: low.freq.toDouble().obs,
        min: low.min_freq.toDouble(),
        max: low.max_freq.toDouble(),
        step: 1,
      ),

      ///低通斜率
      Model(
        title: I19n.i.slope,
        value: low.type!.slope.toDouble().obs,
        min: low.type!.slopeList[0].toDouble(),
        max: low.type!.slopeList[low.type!.slopeList.length - 1].toDouble(),
        step: 6,
      ),
    ];
    list2.value = [
      ///当前频点的序列号
      Model(
        title: I19n.i.number,
        value: (sign.index.toDouble() + 1).obs,
        min: 1,
        max: ch.sign_list.length.toDouble(),
        step: 1,
      ),
      //当前频点的频率
      Model(
        title: I19n.i.frequency,
        value: sign.freq.toDouble().obs,
        min: sign.min_freq.toDouble(),
        max: sign.max_freq.toDouble(),
        step: 1,
      ),
      //当前频点的增益
      Model(
        title: I19n.i.gain,
        value: sign.gain.toDouble().obs,
        min: sign.min_gain,
        max: sign.max_gain,
        step: 0.1,
        isint: false,
      ),
      //当前频点的q值
      Model(
        title: I19n.i.bandwidth,
        value: sign.Q.toDouble().obs,
        min: sign.min_Q,
        max: sign.max_Q,
        step: 0.01,
        isint: false,
      ),
    ];
    setting_config.value =
        [
          I19n.i.factoryReset,
          I19n.i.saveConfig,
          I19n.i.useConfig,
          I19n.i.exportFiles,
          I19n.i.importFiles,
        ].asMap().entries.map(($0) {
          String img = $0.key == 0 ? assets.refresh_black : assets.files_select;
          return {
            $0.value: {'img': img, 'select': false.obs},
          };
        }).toList();
    language_list.value = [I19n.i.chinese, I19n.i.english];
    reset_title.value = I19n.i.reset;
    currentLanguage.value = I19n.getLocalLangCode() == 'en' ? 1 : 0;
  }

  ///选中导航栏的下标
  void selectNavibarIndex(int index, BuildContext? context) {
    currentIndex.value = index;
    if (index == 0) {
      ismute.value = !ismute.value;
      final ch = globalController.rxModel.value.ch_list[0];
      globalController.updateMUTE(ch);
    } else if (index == 1) {
      dialog_app.show(context!);
    } else if (index == 2) {
      dialog_bluetooth.show(context!);
    } else if (index == 3) {
      dialog_setup.show(context!);
    }
  }

  ///滑动条响应方法
  void onSliderChange(Model model, double value, {bool issend = false}) {
    model.value.value = value.roundDouble(model == list2[3] ? 2 : 1);
    _updateRxmodel(model, issend: issend);
  }

  ///步进响应方法
  void onStepChange(Model model, {bool isleft = false}) {
    double v = isleft ? model.value.value - model.step : model.value.value + model.step;
    model.value.value = min(max(model.min, v.roundDouble(model == list2[3] ? 2 : 1)), model.max);
    _updateRxmodel(model);
  }

  void selectSignChange(int index, int freq, double gain, bool isMove) {
    // final current_sgin = globalController.rxModel.value.ch_list[0].sign_list[index];
    // for (var $0 in globalController.rxModel.value.ch_list[0].sign_list) {
    //   $0.select = $0.index == index;
    // }
    // current_sgin.select = true;
    // if (isMove) {
    //   current_sgin.freq = freq;
    //   current_sgin.gain = gain;
    // }
    // globalController.updateSignEQ(current_sgin);
    final model = list2[0];
    model.value.value = min(max(model.min, index.toDouble() + 1), model.max);
    _updateRxmodel(model);
  }

  ///刷新全局模型
  void _updateRxmodel(Model model, {bool issend = true}) {
    final temp_list = [...list1, ...list2];
    final index = temp_list.indexWhere(($0) => $0.title == model.title);
    final ch = globalController.rxModel.value.ch_list[0];
    final low = ch.low_pass!;
    final sign = ch.sign_list.firstWhere(($0) => $0.select, orElse: () => ch.sign_list.first);
    switch (index) {
      case 0:
        globalController.updateDB(ch, model.value.value, isSend: issend);
        break;
      case 1:
        globalController.updatePHASE_Value(ch, model.value.toDouble());
        break;
      case 2:
        globalController.updatePassFreq(low, model.value.value.toInt(), isSend: issend);
        break;
      case 3:
        globalController.updateSlope(low, model.value.toInt());
        break;
      case 4:
        globalController.selectSign(ch.sign_list[model.value.toInt() - 1]);
        onInit();
        break;
      case 5:
        globalController.updateSignFreq(sign, model.value.value, isSend: issend);
        break;
      case 6:
        globalController.updateSignGain(sign, model.value.value, isSend: issend);
        break;
      case 7:
        globalController.updateSignQ(sign, model.value.value, isSend: issend);
        break;
    }
  }

  ///切换 语言
  void changeLanguage(int index) {
    final lang = index == 0 ? 'zh' : 'en';
    I19n.save(lang);
    BluetoothManager.instance.setLocalLanguage(lang);
    currentLanguage.value = index;
    onInit();
  }

  ///恢复出厂设置
  void reset() {
    globalController.resetEQ();
    globalController.resetHi_LowPass();
    onInit();
  }

  ///复位当前频点到默认值
  void resetSign() {
    onSliderChange(list2[1], CHDefaultConfig().signList![list2[0].value.value.toInt() - 1].toDouble(), issend: true);
    onSliderChange(list2[2], CHDefaultConfig().sign_sample.gain, issend: true);
    onSliderChange(list2[3], CHDefaultConfig().sign_sample.Q, issend: true);
  }

  Future<void> setupSelection(int index, BuildContext? context) async {
    switch (index) {
      case 0:
        final reset = DialogAlert(content: I19n.i.resetTitle);
        reset.show(context!);
        reset.onEnter = () {
          this.reset();
        };
        break;
      case 1:
        final map = setting_config[index];
        final select = map.values.first['select'].value;
        map.values.first['select'].value = !select;
        final map2 = setting_config[index + 1];
        map2.values.first['select'].value = false;
        // setting_config.value = [...setting_config];
        break;
      case 2:
        final map = setting_config[index];
        final select = map.values.first['select'].value;
        map.values.first['select'].value = !select;
        final map2 = setting_config[index - 1];
        map2.values.first['select'].value = false;
        // setting_config.value = [...setting_config];
        break;
      case 3:
        final input = DialogInput();
        input.show(context!);
        input.onEnter = (name) {
          globalController.saveFile(name);
        };
        break;
      case 4:
        globalController.loadFile(context!, () {
          onInit();
        });
        break;
      default:
    }
  }

  ///调用 或者使用 config
  void saveOrUseConfig(int index, int config_index, BuildContext context) {
    final title = index == 1 ? I19n.i.savetips : I19n.i.usetips;
    final alert = DialogAlert(content: title);
    alert.show(context);
    alert.onEnter = () {
      ///保存配置
      if (index == 1) {
      } else {
        //使用配置
      }
    };
  }
}
